import pandas as pd
import tkinter as tk
from tkinter import filedialog, messagebox
import os

class ExcelMerger:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Excel文件合并工具")
        self.window.geometry("600x400")
        
        # 设置窗口样式
        self.window.configure(bg='#f0f0f0')
        
        # 创建主框架
        self.main_frame = tk.Frame(self.window, bg='#f0f0f0')
        self.main_frame.pack(padx=20, pady=20, fill='both', expand=True)
        
        # 源文件选择
        self.source_label = tk.Label(self.main_frame, text="源Excel文件：", bg='#f0f0f0')
        self.source_label.pack(anchor='w')
        
        self.source_frame = tk.Frame(self.main_frame, bg='#f0f0f0')
        self.source_frame.pack(fill='x', pady=(0, 10))
        
        self.source_path = tk.StringVar()
        self.source_entry = tk.Entry(self.source_frame, textvariable=self.source_path, width=50)
        self.source_entry.pack(side='left', padx=(0, 10))
        
        self.source_button = tk.Button(self.source_frame, text="浏览", command=self.select_source_file)
        self.source_button.pack(side='left')
        
        # 目标文件选择
        self.target_label = tk.Label(self.main_frame, text="目标Excel文件：", bg='#f0f0f0')
        self.target_label.pack(anchor='w')
        
        self.target_frame = tk.Frame(self.main_frame, bg='#f0f0f0')
        self.target_frame.pack(fill='x', pady=(0, 20))
        
        self.target_path = tk.StringVar()
        self.target_entry = tk.Entry(self.target_frame, textvariable=self.target_path, width=50)
        self.target_entry.pack(side='left', padx=(0, 10))
        
        self.target_button = tk.Button(self.target_frame, text="浏览", command=self.select_target_file)
        self.target_button.pack(side='left')
        
        # 合并按钮
        self.merge_button = tk.Button(self.main_frame, text="开始合并", command=self.merge_files,
                                    bg='#4CAF50', fg='white', width=20, height=2)
        self.merge_button.pack(pady=20)
        
        # 状态显示
        self.status_label = tk.Label(self.main_frame, text="", bg='#f0f0f0', wraplength=500)
        self.status_label.pack(pady=10)

    def select_source_file(self):
        filename = filedialog.askopenfilename(
            title="选择源Excel文件",
            filetypes=[("Excel files", "*.xlsx *.xls")]
        )
        if filename:
            self.source_path.set(filename)

    def select_target_file(self):
        filename = filedialog.askopenfilename(
            title="选择目标Excel文件",
            filetypes=[("Excel files", "*.xlsx *.xls")]
        )
        if filename:
            self.target_path.set(filename)

    def merge_files(self):
        source_path = self.source_path.get()
        target_path = self.target_path.get()
        
        if not source_path or not target_path:
            messagebox.showerror("错误", "请选择源文件和目标文件")
            return
            
        try:
            # 读取源文件和目标文件
            source_df = pd.read_excel(source_path)
            target_df = pd.read_excel(target_path)
            
            # 合并数据框
            merged_df = pd.concat([target_df, source_df], ignore_index=True)
            
            # 生成新的文件名
            dir_name = os.path.dirname(target_path)
            base_name = os.path.splitext(os.path.basename(target_path))[0]
            new_file_path = os.path.join(dir_name, f"{base_name}_merged.xlsx")
            
            # 保存合并后的文件
            merged_df.to_excel(new_file_path, index=False)
            
            self.status_label.config(
                text=f"合并成功！\n新文件保存为：{new_file_path}",
                fg="green"
            )
            messagebox.showinfo("成功", f"文件已成功合并并保存为：\n{new_file_path}")
            
        except Exception as e:
            self.status_label.config(
                text=f"合并失败：{str(e)}",
                fg="red"
            )
            messagebox.showerror("错误", f"合并过程中出现错误：\n{str(e)}")

    def run(self):
        self.window.mainloop()

if __name__ == "__main__":
    app = ExcelMerger()
    app.run()
